<template>
  <j-modal
    switchFullscreen
    :width='800'
    :title='title'
    :visible='visible'
    @cancel='handleCancel'
    @ok='handleOk'
    :confirmLoading='confirmLoading'
  >
    <template slot='footer'>
      <a-button @click='handleCancel'>取消</a-button>
      <a-button v-if='!disableSubmit' :loading="confirmLoading" type='primary' @click='handleOk'>确认</a-button>
    </template>
    <a-divider style='font-weight: 600' orientation='left'>基础信息</a-divider>
    <a-form :form='form'>
      <!--      <a-row :gutter="24">-->
      <!--        <a-col :span="12">-->
      <a-form-item
        :labelCol='{  xs: { span: 5 },sm: { span: 5 },}'
        :wrapperCol='{ xs: { span:14 }, sm: { span: 15}}'
        label='自定义产品组名称'
        >
        <a-input style='width: 96%' :disabled='disableSubmit' placeholder='请输入自定义产品组名称'
                 v-decorator="['productGroupName', validatorRules.productGroupName]" />
      </a-form-item>
      <!--        </a-col>-->
      <!--        <a-col :span="24">-->
      <a-form-item
        :labelCol='{  xs: { span: 5 },sm: { span: 5 },}'
        :wrapperCol='{ xs: { span: 12 }, sm: { span: 18 }}'
        label='备注'
        >
        <a-textarea style='height: 80px;width: 80%' :maxLength='500' placeholder='请输入备注'
                    :disabled='disableSubmit' v-decorator="['remarks']" />
      </a-form-item>
      <!--        </a-col>-->
      <!--      </a-row>-->
    </a-form>
    <a-divider style='font-weight: 600;margin-top: -20px;' orientation='left'>添加商品</a-divider>
    <div style='width:90%;margin-left:5%;border: 1px solid #F1F1F1'>
      <div>
        <a-button style='margin: 10px 30px 0px 30px;' @click='handleAdd' type='primary' :disabled='disableSubmit'>新增</a-button>
      </div>
      <div style='padding: 30px;width: 100%'>
        <a-table
          ref='table'
          size='middle'
          bordered
          rowKey='id'
          :columns='columns'
          :dataSource='dataSource'
          :pagination='ipagination'
          :loading='loading'
          :scroll='{x:400,y:250 }'
          :rowSelection='{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}'
          @change='handleTableChange'>
        <span slot='action' slot-scope='text, record' v-if='!disableSubmit'>
           <a style='color: red;' @click='handleDelete(record)'>删除</a>
        </span>
          <span slot='action' slot-scope='text, record' v-else>
           <span style='color: #9a9494;' >删除</span>
        </span>
        </a-table>
      </div>
    </div>
    <my-shuttle-modal
      ref='shuttleModal'
      title='选择商品'
      :keyVal="'productName'"
      :columns='columnsModal'
      :columns2='columnsModal2'
      leftUrl='/goods/cnGoods/findPageList'
      :searchConfig='searchConfig'
      @chooseOk='chooseOk'
    ></my-shuttle-modal>
    <!--    <proChose ref="prochoose" @okbro="okbropro"></proChose>-->
  </j-modal>
</template>

<script>
import { pick } from 'lodash'
import { getAction, postAction } from '@/api/manage'
import myShuttleModal from '../../../../components/cn-components/CnShuttleModal'

export default {
  name: 'cusproModal',
  components: { myShuttleModal },
  data() {
    return {

      disableSubmit: false,
      title: '新增',
      searchConfig: [
        {
          type: 'select',
          name: 'classifyCode',
          isRequest: true,
          keyName: 'classifyCode',
          url: '/goodsclassify/cnGoodsClassify/findPageList',
          valName: 'classifyName',
          placeholder: '请选择商品层级',
          options: []
        },
        {
          type: 'input',
          name: 'goodsName',
          placeholder: '请输入商品名称'
        },
        {
          type: 'input',
          name: 'goodsCode',
          placeholder: '请输入商品编号'
        }
      ],
      columnsModal: [

        {
          title: '商品编号',
          align: 'center',
          dataIndex: 'goodsCode'
        },
        {
          title: '商品名称',
          align: 'center',
          dataIndex: 'goodsName'
        }
      ],
      columnsModal2: [
        {
          title: '商品编号',
          align: 'center',
          dataIndex: 'goodsCode'
        },
        {
          title: '商品名称',
          align: 'center',
          dataIndex: 'goodsName'
        },
        {
          title: '操作',
          dataIndex: 'action',
          // fixed: 'right',
          align: 'center',
          scopedSlots: {
            customRender: 'delete'
          }
        }
      ],
      confirmLoading: false,
      form: this.$form.createForm(this),
      model: {},
      visible: false,
      /* 数据源 */
      dataSource: [],
      /* table选中keys*/
      selectedRowKeys: [],
      /* table选中records*/
      selectionRows: [],
      /* 分页参数 */
      ipagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30', '40', '50'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        }
      },
      model: {},
      loading: false,
      labelCol: {
        xs: { span: 6 },
        sm: { span: 6 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 }
      },
      columns: [
        {
          title: '商品编号',
          align: 'center',
          dataIndex: 'goodsCode'
        },
        {
          title: '商品名称',
          align: 'center',
          dataIndex: 'goodsName'
        },
        {
          title: '操作',
          dataIndex: 'action',
          fixed: 'right',
          align: 'center',
          width: 150,
          scopedSlots: {
            customRender: 'action'
          }
        }
      ],
      url: {
        // kuaidi: window._CONFIG['domianOrderURL'] + '/cnDictionaryTypeController/getDictionaryTypeList'
        sendOrder: window._CONFIG['domianURL'] + '/material/saveOrUpdate',
        queryById: '/product-center/cnProductGroup/getInfo'
      },
      validatorRules: {
        productGroupName: {
          rules: [
            { required: true, message: '' }
          ]
        },
        remarks: {
          rules: [
            { required: true, message: '' }
          ]
        }
      }
    }

  },
  methods: {
    handleAdd() {
      this.$refs.shuttleModal.visible = true
      this.$refs.shuttleModal.handleSelect()
      this.dataSource.forEach(item => {
        this.$refs.shuttleModal.dataSource2.push({ goodsCode: item.goodsCode, goodsName: item.goodsName })
      })
      this.$refs.shuttleModal.loadData()
    },
    add() {
      this.visible = true
      this.edit()
    },
    edit(isEdit = {}) {
      this.form.resetFields()
     if(isEdit){
       getAction(this.url.queryById, { id: isEdit.id }).then((res) => {
         if (res.success) {
           let record = res.result
           this.ProductAdress = []
           // this.form.resetFields()
           console.log(record)
           this.model = Object.assign({}, record)
           if (record.productGroupItems) {
             this.dataSource = [...record.productGroupItems]
           }
           this.visible = true
           let fieldsVal = pick(this.model, 'productGroupName', 'remarks')
           this.$nextTick(() => {
             this.visible = true
             this.form.setFieldsValue(fieldsVal)
           })
         }
       })

     }

    },
    handleDelete(e) {
      let key = this.dataSource.map(item => {
        return item.id
      })
      this.dataSource.splice(key.indexOf(e.id), 1)
    },
    chooseOk(e) {
      let key = this.dataSource.map(item => item.goodsCode)
      e.forEach(item => {
        if (key.indexOf(item.goodsCode) == -1) {
          this.dataSource.push(item)
        }
      })
    },
    onSelectChange(selectedRowKeys, selectionRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectionRows = selectionRows
    },
    handleOk() {
      let that = this
      this.form.validateFields((err, values) => {
        if (!err) {
          that.confirmLoading = true
          let formData = Object.assign(that.model, values)
          formData.productGroupItems = this.dataSource
          console.log(formData)
          postAction('/product-center/cnProductGroup/saveOrUpdate', formData).then((res) => {
            if (res.success) {
              that.$message.success(res.message, 2)
              that.$emit('ok')
              that.close()
            } else {
              that.$message.error(res.message, 2)
            }
          }).finally(() => {
            that.confirmLoading = false
          })

        }
      })
    },
    handleTableChange(pagination, filters, sorter) {
      //分页、排序、筛选变化时触发
      //TODO 筛选
      if (Object.keys(sorter).length > 0) {
        this.isorter.column = sorter.field
        this.isorter.order = 'ascend' == sorter.order ? 'asc' : 'desc'
      }
      if (this.ipagination.current !== pagination.current) {
        this.selectionRows = []
        this.selectedRowKeys = []
      }
      this.ipagination = pagination
      // this.loadData()
    },
    handleCancel() {
      this.form.resetFields()
      this.visible = false
      this.confirmLoading = false
      this.dataSource = []
    },
    close() {
      this.handleCancel()
    }
  }
}
</script>

<style scoped>

</style>